//
//  ComicViewController.m
//  Comic
//
//  Created by Andy.He on 16/3/10.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "ComicViewController.h"
#import "ComicTableViewCell.h"
#import "ComicCollectionCell.h"
#import "ComiContentViewController.h"
#import "AuthorViewController.h"
#import "DetailViewController.h"
#import "UserModel.h"
#import "TopicModel.h"
#import "ComicModel.h"

#define COMIC_DETAIL_URL @"http://api.kuaikanmanhua.com/v1/daily/comic_lists/0?since=0"
#define COMIC_DATE_URL @"http://api.kuaikanmanhua.com/v1/daily/comic_lists/"

@interface ComicViewController () <UITableViewDataSource,UITableViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (strong, nonatomic) IBOutlet UIView *headerView;

@property (strong, nonatomic) IBOutlet UICollectionViewFlowLayout *dateFlowlayout;
@property (strong, nonatomic) IBOutlet UICollectionView *dateCollection;
@property (strong, nonatomic) IBOutlet UITableView *comicTableView;

@property (strong ,nonatomic) NSMutableArray *comicDataArr;
@property (strong ,nonatomic) NSMutableArray *timeDataArr;
@property (strong ,nonatomic) NSMutableArray *topicDataArr;
@property (strong ,nonatomic) NSMutableArray *userDataArr;
@property (strong ,nonatomic) NSMutableArray *dateArr;

@property (strong ,nonatomic) UserModel *userMod;
@property (strong ,nonatomic) ComicModel *comicMod;
@property (strong ,nonatomic) TopicModel *topicMod;


@end

@implementation ComicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"推荐";

    [self collectionAndTable];
    [self dataJson];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.992 green:0.906 blue:0.235 alpha:1.000];
    
}
#pragma mark 16位颜色转换
- (UIColor *)getColor:(NSString *)hexColor
{
    unsigned int red,green,blue;
    NSRange range;
    range.length = 2;
    
    range.location = 1;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&red];
    
    range.location = 3;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&green];
    
    range.location = 5;
    [[NSScanner scannerWithString:[hexColor substringWithRange:range]] scanHexInt:&blue];
    
    return [UIColor colorWithRed:(float)(red/255.0f) green:(float)(green / 255.0f) blue:(float)(blue / 255.0f) alpha:1.0f];
}

#pragma mark 头部collection
- (void)collectionAndTable{
    [self.comicTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ComicTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ComicTableViewCell class])];
    [self.dateCollection registerNib:[UINib nibWithNibName:NSStringFromClass([ComicCollectionCell class])  bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([ComicCollectionCell class])];
    self.dateFlowlayout.minimumInteritemSpacing = 0;
    self.dateFlowlayout.minimumLineSpacing = 0;
    self.dateFlowlayout.itemSize = CGSizeMake(SCREEN_WIDTH / 7, 40);
    self.dateCollection.collectionViewLayout = self.dateFlowlayout;
    self.dateCollection.backgroundColor = [UIColor whiteColor];
    self.comicTableView.tableHeaderView = self.headerView;
}

- (void)dataJson{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:COMIC_DETAIL_URL parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        

        self.comicDataArr = [NSMutableArray array];
        self.timeDataArr = [NSMutableArray array];
        self.topicDataArr = [NSMutableArray array];
        self.userDataArr = [NSMutableArray array];
        self.dateArr = [NSMutableArray array];

        for (NSDictionary *dic in responseObject[@"data"][@"comics"]) {
            ComicModel *mod = [[ComicModel alloc] init];
            [mod setValuesForKeysWithDictionary:dic];
            [self.comicDataArr addObject:mod];
            
            TopicModel *topicMod = [[TopicModel alloc] init];
            [topicMod setValuesForKeysWithDictionary:dic[@"topic"]];
            [self.topicDataArr addObject:topicMod];
            
            UserModel *userMod = [[UserModel alloc] init];
            [userMod setValuesForKeysWithDictionary:dic[@"topic"][@"user"]];
            [self.userDataArr addObject:userMod];

        }
        NSNumber *number = responseObject[@"data"][@"timestamp"];
        for (NSInteger i = 6; i >= 0; i--) {
            NSString *dateStr = [NSString new];
            if (i == 0) {
                dateStr = @"今天";
                [self.timeDataArr addObject:dateStr];
            }else if(i == 1){
                dateStr = @"昨天";
                [self.timeDataArr addObject:dateStr];
            }else{
                // 计算是周几
                NSInteger dateNum =  [number integerValue] - 24 * 60 * 60 * i;
                [self.timeDataArr addObject:[self getWeekDayFordate:dateNum]];
            }
            NSNumber *numStr = [[NSNumber alloc] initWithInteger:[number integerValue] - 24 * 60 * 60 * i];
            [self.dateArr addObject:numStr];
        }
        [self.comicTableView reloadData];
        [self.dateCollection reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
}

#pragma mark 日期数据解析
- (void)dateDataJson:(NSString *)urlStr{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *urlString = [NSString stringWithFormat:@"%@?since=0",urlStr];
        NSString *new = [NSString stringWithFormat:@"%@%@",COMIC_DATE_URL,urlString];
    [manager GET:new parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.comicDataArr = [NSMutableArray array];
        self.topicDataArr = [NSMutableArray array];
        self.userDataArr = [NSMutableArray array];
        
        
        for (NSDictionary *dic in responseObject[@"data"][@"comics"]) {
            ComicModel *mod = [[ComicModel alloc] init];
            [mod setValuesForKeysWithDictionary:dic];
            [self.comicDataArr addObject:mod];
            
            TopicModel *topicMod = [[TopicModel alloc] init];
            [topicMod setValuesForKeysWithDictionary:dic[@"topic"]];
            [self.topicDataArr addObject:topicMod];
            
            UserModel *userMod = [[UserModel alloc] init];
            [userMod setValuesForKeysWithDictionary:dic[@"topic"][@"user"]];
            [self.userDataArr addObject:userMod];
            
        }
        
        [self.comicTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    
    }];
    
}

// 换算日期数组
- (NSString *)getWeekDayFordate:(NSInteger)data
{
    NSArray *weekday = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:data];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [calendar components:NSCalendarUnitWeekday fromDate:newDate];
    
    NSString *weekStr = [weekday objectAtIndex:components.weekday];
    return weekStr;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.comicDataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ComicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ComicTableViewCell class]) forIndexPath:indexPath];
    ComicModel *comicMod = self.comicDataArr[indexPath.row];
    TopicModel *topicMod = self.topicDataArr[indexPath.row];
    UserModel *userMod = self.userDataArr[indexPath.row];
    
    cell.typeLabel.text = comicMod.label_text;
    cell.typeLabel.textColor = [self getColor:comicMod.label_text_color];
    cell.typeLabel.backgroundColor = [self getColor:comicMod.label_color];
    
    cell.titleLabel.text = topicMod.title;
    cell.detailLabel.text = comicMod.title;
    
    cell.titleBtn.tag = indexPath.row + 4000;
    [cell.titleBtn addTarget:self action:@selector(pushToDetail:) forControlEvents:UIControlEventTouchUpInside];
    
    [cell.authorBtn setTitle:userMod.nickname forState:UIControlStateNormal];
    cell.authorBtn.tag = indexPath.row + 3000;
    [cell.authorBtn addTarget:self action:@selector(passValue:) forControlEvents:UIControlEventTouchUpInside];
    
    // 接口750的图片无法显示,所以换成640
    NSString *strUrl = [comicMod.cover_image_url stringByReplacingOccurrencesOfString:@"750" withString:@"640"];
    [cell.mainImageView setImageWithURL:[NSURL URLWithString:strUrl] placeholderImage:[UIImage imageNamed:@"fakeimg"]];
    return cell;
}

- (void)pushToDetail:(UIButton *)btn{
    NSInteger index = btn.tag - 4000;
    TopicModel *topicMod = self.topicDataArr[index];
    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:NSStringFromClass([DetailViewController class]) bundle:nil];
    detailVC.headerData = topicMod;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)passValue:(UIButton *)btn{
    NSInteger index = btn.tag - 3000;
    UserModel *userMod = self.userDataArr[index];
    AuthorViewController *authorVC = [[AuthorViewController alloc] initWithNibName:NSStringFromClass([AuthorViewController class]) bundle:nil];
    authorVC.authorUrl = userMod.idNumber;
    [self.navigationController pushViewController:authorVC animated:YES];

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 300;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ComicModel *comicMod = self.comicDataArr[indexPath.row];
    ComiContentViewController *comicVC = [[ComiContentViewController alloc] init];
    comicVC.nameTitle = comicMod.title;
    comicVC.idNUmber = comicMod.idNumber;
    [self.navigationController pushViewController:comicVC animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.timeDataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ComicCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ComicCollectionCell class]) forIndexPath:indexPath];
    cell.lineView.hidden = YES;
    NSString *str = self.timeDataArr[indexPath.row];
    if (indexPath.row == 6) {
        cell.lineView.hidden = NO;
        cell.dateLabel.textColor = [UIColor colorWithRed:0.992 green:0.796 blue:0.258 alpha:1.000];
    }
    cell.dateLabel.text = str;
    cell.backgroundColor = [UIColor colorWithWhite:0.979 alpha:1.000];
    return cell;
}
#pragma mark  头部颜色变换
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    ComicCollectionCell *cell = (ComicCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.dateLabel.textColor = [UIColor blackColor];
    cell.lineView.hidden = YES;
}

#pragma mark  头部颜色变换
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ComicCollectionCell *cell = (ComicCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSString *urlStr = self.dateArr[indexPath.row];
    cell.lineView.hidden = NO;
    cell.dateLabel.textColor = [UIColor colorWithRed:0.992 green:0.796 blue:0.258 alpha:1.000];
    if(indexPath.row < 6){
        ComicCollectionCell *cell = (ComicCollectionCell *)[collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:6 inSection:0]];
        cell.dateLabel.textColor = [UIColor blackColor];
        cell.lineView.hidden = YES;
        [self dateDataJson:urlStr];
    }else{
    [self dataJson];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
